package cn.dankal.flyaudio.personal

import android.view.View
import api.UserServiceFactory
import butterknife.OnClick
import cn.dankal.basiclib.DKUserManager
import cn.dankal.basiclib.base.activity.BaseActivity
import cn.dankal.basiclib.common.sms.SmsCodeImpl
import cn.dankal.basiclib.protocol.PersonalProtocol
import cn.dankal.basiclib.rx.AbstractDialogSubscriber
import cn.dankal.basiclib.util.StringUtil
import cn.dankal.basiclib.util.ToastUtils
import cn.dankal.basiclib.widget.titlebar.SingleTextTitle
import cn.dankal.business.Constants
import cn.dankal.business.pojo.ReasonBean
import cn.dankal.flyaudio.R
import com.alibaba.android.arouter.facade.annotation.Route
import com.jeremyliao.liveeventbus.LiveEventBus
import kotlinx.android.synthetic.main.activity_getcode.*

@Route(path = PersonalProtocol.MODIFY_EMAIL)
class ModifyEmailActivity : BaseActivity() {
    var email: String? = null
    var smsCode = SmsCodeImpl(this)
    var singleTextTitle = SingleTextTitle("编辑邮箱")

    override fun getLayoutId(): Int {
        return R.layout.activity_getcode
    }

    override fun initComponents() {
        addTitleBar(singleTextTitle)
        tv_tips.setText("请输入该邮箱收到的验证码")
        email = intent.getStringExtra("email")
        et_mobile.setText(email)
    }


    @OnClick(R.id.bt_code, R.id.bt_next)
    fun onViewClicked(view: View) {
        when (view.id) {
            R.id.bt_code -> smsCode.getCode(email, bt_code, Constants.CheckType.Email.states.toString())
            R.id.bt_next -> {
                val code = et_code.getText().toString()
                if (!StringUtil.isValid(code)) {
                    ToastUtils.showShort("请输入验证码")
                    return
                }
                bindEmail(code)
            }
        }
    }

    private fun bindEmail(code: String) {
        var maps = hashMapOf("code" to code, "fgToken" to DKUserManager.getUserInfo().fgToken, "newEmail" to email, "userId" to DKUserManager.getUserInfo().id)
        UserServiceFactory.changeEmail(maps).subscribe(object : AbstractDialogSubscriber<ReasonBean>(this) {
            override fun onNext(reasonBean: ReasonBean) {
                ToastUtils.showShort("邮箱成功修改")
                val userInfoBean = DKUserManager.getUserInfo()
                userInfoBean.email = email
                DKUserManager.updateUserInfo(userInfoBean)
                LiveEventBus.get("update_user_info", String::class.java).post("")
                finish()
            }
        })
    }

    override fun onDestroy() {
        super.onDestroy()
        smsCode.onDestory()
    }
}
